package com.sti.platform.service.impl;

import java.io.InputStream;
import java.lang.management.BufferPoolMXBean;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sti.platform.util.UtilReflex;
import com.sti.platform.util.excel.UtilExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aisino.core.server.BaseService;
import com.aisino.tools.enums.PageEnum;
import com.aisino.tools.enums.QlEnum;
import com.aisino.tools.util.Assert;
import com.aisino.tools.util.RandomUtils;
import com.aisino.tools.util.StringUtils;
import com.aisino.tools.util.page.Page;
import com.aisino.tools.util.page.Pagination;
import com.sti.platform.dao.NoticeDao;
import com.sti.platform.model.Notice;
import com.sti.platform.model.User;
import com.sti.platform.service.NoticeService;
import com.sti.platform.util.UtilDate;
import org.springframework.web.multipart.MultipartFile;

@Service
public class NoticeServiceImpl extends BaseService implements NoticeService {

	@Autowired
	private NoticeDao noticeDao;
	
	@Override
	public List<Notice> getAllNotice() {
		return noticeDao.getAllNotice();
	}
	
	@Override
	public List<Notice> getNoticeByParam( String params[],Object values[]) {
		String sql  = "SELECT * FROM sys_notice WHERE 1=1 AND title LIKE:title ";
		return noticeDao.getNoticeByParam(sql, params, values);
	}

	@Override
	public Notice getNoticeByID(String id) {
		return noticeDao.getNoticeByID(id);
	}

	
	@Override
	public List<Notice> getNoticeByPage(Notice notice, String page, String row) {

		//反射获取参数
		Map map = UtilReflex.reflexModel(notice);// params --> values 一定是一对一有值的
		String params[] = (String[])map.get("params");//参数 数组
		Object values[] = (Object[])map.get("values");//参数值  数组
		String sql  = " ";
		StringBuffer sb = new  StringBuffer();
		sb.append("SELECT * FROM sys_notice WHERE 1=1 ");//基础查询

		if(params!=null && params.length>0){//有参数，这里只做 标题查询
			for(int i=0;i<params.length;i++){
				String para = params[i];
				if(para.equals("enddate")){//按 结束时间 查询 Arrays.asList(params).contains("enddate") listParams.contains("enddate")
					sb.append(" AND enddate >=:enddate ");
				}else if(para.equals("startdate")){//开始时间
					sb.append(" AND startdate <=:startdate ");
				}else{//其他，均为模糊查询
					values[i] = "%"+values[i]+"%";
					sb.append(" AND "+para+" LIKE:"+para+" ");
				}
			}
		}
		sb.append(" ORDER BY createtime DESC ");//按照时间降序
		sql = sb.toString();
		Page pageModel = new Pagination();
		Integer nowPage = changStingNum(page,1);//当前页
		Integer nowRow =  changStingNum(row,10);//当前页最大数据量
		Integer total = noticeDao.getNoticeNum(sql,params,values);
		Integer totalPage =  (total%nowRow==0) ? (total/nowRow) :  ((total/nowRow) +1);//总页数
		nowPage = (nowPage >=totalPage) ? totalPage : nowPage ;//当前页，判读
		pageModel.setPage(nowPage);//当前页数
		pageModel.setRow(nowRow);//每页多少条
		pageModel.setTotal(total);
		//1000代表取  PageEnum.PAGE_TOP的时候 的top数量
		return noticeDao.getNoticeByPage(sql, params, values, 1000, pageModel, QlEnum.SQL, PageEnum.PAGE_YES);
	}

	/**
	 * 使用工具，根据传递的 object 判断是不是数字，是数字转换成数字，不
	 * 是数字，返回自己指定的数字，不指定默认为1
	 * @param returnNum
	 * @return
	 */


		public Integer changStingNum(String numStr,Integer returnNum){
			if(returnNum==null){
				returnNum = 1;
			}
			if(numStr!=null && !"".equals(numStr) && numStr.matches("^\\d+$")){//是数字
				returnNum = Integer.valueOf(numStr);
			}
			return returnNum;
		}

	@Override
	public void saveNotice(Notice notice) {
		//从 session 中获取 用户的信息
		User user = new User();
		user.setId("adminid123456");
		user.setRealName("管理员");
		// RandomUtils.randomUUID() ;
		//uuid
		notice.setCreateuserid(user.getId());
		//创建人
		notice.setCreateusername(user.getRealName());
		//创建时间
		notice.setCreatetime(UtilDate.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
		//断言的形式进行，校验
		//Assert.isTrue(StringUtils.hasText(notice.getTitle()), "标题不能为空.");
		super.save(notice);
	}

	/**
	 * 根据String ids[]批量删除
	 * 批量删除，id 是 , 组合的/支持符串,批量
	 * @param id
	 */
	@Override
	public void delNotice(String id) {
		String[] ids = id.split(",");
		if(ids.length>1){//多条删除
			noticeDao.delNotice(ids);
		}else{
			noticeDao.delNotice(id);
		}
	}
	/**
	 * 根据String ids[]批量删除
	 * 批量删除，id 是 , 组合的
	 * @param ids
	 */
	@Override
	public void delNotice(String[] ids) {
		noticeDao.delNotice(ids);
	}

	@Override
	public void updateNotice(Notice notice) {
		//从 session 中获取 用户的信息
		User user = new User();
		user.setId("updateadminid123456");
		user.setRealName("Update管理员");
		//断言的形式进行，校验
		//Assert.isTrue(StringUtils.hasText(notice.getTitle()), "标题不能为空.");
		super.update(notice);
		
	}

	@Override
	public void exportNotice(Notice notice,HttpServletResponse response) {
		UtilExcel<Notice> ue = new UtilExcel(Notice.class);
		List<Notice> list = new ArrayList<Notice>();
		String sql = " select * from sys_notice where 1=1 ";
		if(notice!=null && notice.getType()!=null ){
			sql = sql + " and type ="+notice.getType();
		}
		sql += " order by createtime desc ";
		list = noticeDao.getNoticeByParam(sql,null,null);
		try{
			if(list.isEmpty()){//空
				Notice bean = new Notice();
				bean.setContent("暂无数据");
				list.add(bean);
			}
			ue.getListToExcel(list,"通知公告","通知公告",response);
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	@Override
	public void importNotice(MultipartFile file) {
		try{
			//转换成输入流
			InputStream is = file.getInputStream();

			UtilExcel<Notice> ue = new UtilExcel(Notice.class);
			List<Notice> list = new ArrayList<Notice>();
			list = ue.getExcelToList(file);
			System.out.println(list);
		}catch (Exception e){
			e.printStackTrace();
		}
	}


}
